package com.cys.dm.controller;

import com.alibaba.fastjson.JSON;
import com.cys.dm.entity.user.DmUser;
import com.cys.dm.exceptions.DmException;
import com.cys.dm.server.DmUserServer;
import com.cys.dm.utils.MD5;
import com.cys.dm.utils.UserAgentUtil;
import com.cys.dm.vo.CommonResponse;
import com.cys.dm.vo.UserTokenResponse;
import com.cys.dm.vo.VoUtil;
import cz.mallat.uasparser.UASparser;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RabbitListener(queues = "dmsms")
public class DmUserController {

    @Autowired
    private DmUserServer dmUserServer;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping(path = "/msg/login")
    public CommonResponse<UserTokenResponse> login(@RequestBody HashMap<String, String> map,
                                        HttpServletRequest request) throws Exception{
        //判断验证码是否正确
        if (map.get("vcode").trim().equals("")){
            throw new DmException("请输入验证码","1001");
        }
        String correctCod = (String) redisTemplate.opsForValue().get(map.get("phone")+":code");
        if (!correctCod.equals(map.get("vcode"))){
            throw new DmException("验证码不匹配","1002");
        }
        //根据用户手机号查询用户信息
        DmUser dmUser = dmUserServer.loginByVerification(map.get("phone"));
        //JWT
        //自定义token
        StringBuffer stringBuffer = new StringBuffer("token:PC-");
        stringBuffer.append(dmUser.getPhone()+"-");
        stringBuffer.append(dmUser.getId()+"-");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date genDate = new Date();
        String genTime = dateFormat.format(genDate);
        stringBuffer.append(genTime+"-");
        UASparser uaSparser =  UserAgentUtil.getUasParser();
        String userAgent = request.getHeader("User-Agent");
        stringBuffer.append(MD5.getMd5(uaSparser.parse(userAgent).getDeviceType(),6));

        //redis存储token
        redisTemplate.opsForValue().set(stringBuffer.toString(), JSON.toJSONString(dmUser),2,TimeUnit.HOURS);

        UserTokenResponse userTokenResponse = new UserTokenResponse();
        userTokenResponse.setUserId(dmUser.getId());
        userTokenResponse.setSex(dmUser.getSex());
        userTokenResponse.setIdCard(dmUser.getIdCard());
        userTokenResponse.setNickName(dmUser.getNickName());
        userTokenResponse.setRealName(dmUser.getRealName());
        userTokenResponse.setPhone(dmUser.getPhone());
        userTokenResponse.setToken(stringBuffer.toString());
        userTokenResponse.setGenTime(genDate.getTime());
        userTokenResponse.setExtTime(genDate.getTime()+(1000 * 60 * 60 * 2));

        return VoUtil.returnSuccess("登录成功",userTokenResponse);
    }

    @RabbitHandler
    public void send(Map<String,String> map){
        //短信验证码
        System.out.println("短信验证码"+map.get("code"));
        /**阿里云 短信服务
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GBbKgnAWwyqTizHcuub", "pK9HYu1s9tcYuxl2LUGHnTEp6oEnNs");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", map.get("phone"));
        request.putQueryParameter("SignName", "yunsong");
        request.putQueryParameter("TemplateCode", "SMS_193520375");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+map.get("code")+"\"}");
        try {
            com.aliyuncs.CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }*/

    }

    @ExceptionHandler(value = DmException.class)
    public CommonResponse aa(DmException e){
        return VoUtil.returnFail(e);
    }

    //使用短信验证码登录
    @PostMapping(path = "/msg")
    public CommonResponse<Object> msg(@RequestBody Map<String,String> param){
        if (redisTemplate.opsForValue().get(param.get("phone")+":vcode")!=null){
            throw new DmException("同一个手机号码60秒内只能发一次验证","1004");
        }
        //生成随机数
        int min = 100000;
        int max = 999999;
        Random random = new Random();
        int code = random.nextInt(max);
        code = code <min ? code+min : code;
        Map<String,String> map = new HashMap<>();
        map.put("phone",param.get("phone"));
        map.put("code",code+"");
        //上传到rabbitmq消息队列
        rabbitTemplate.convertAndSend("dmsms",map);
        //redis
        redisTemplate.opsForValue().set(param.get("phone")+":code",code+"",60, TimeUnit.SECONDS);
        //短信发送使用2s
        return VoUtil.returnSuccess("发送验证码成功",null);
    }

    /**
     * 发送注册验证码
     * @return
     */
    @PostMapping(path = "/code")
    public CommonResponse<Object> code(@RequestBody Map<String,String> param){
        if (redisTemplate.opsForValue().get(param.get("phone")+":dmreg")!=null){
            throw new DmException("同一个手机号码60秒内只能发一次验证","1004");
        }
        //生成随机数
        int min = 100000;
        int max = 999999;
        Random random = new Random();
        int code = random.nextInt(max);
        code = code <min ? code+min : code;
        Map<String,String> map = new HashMap<>();
        map.put("phone",param.get("phone"));
        map.put("code",code+"");
        //上传到rabbitmq消息队列
        rabbitTemplate.convertAndSend("dmreg",map);
        //redis
        redisTemplate.opsForValue().set(param.get("phone")+":dmreg",code+"",60, TimeUnit.SECONDS);
        //短信发送使用2s
        return VoUtil.returnSuccess("发送验证码成功",null);
    }


    /**
     * 注册信息
     * @param map
     * @return
     */
    @PostMapping(path = "/register")
    public CommonResponse<Integer> register(@RequestBody HashMap<String, String> map){
        //判断验证码是否正确
        if (map.get("vcode").trim().equals("")){
            throw new DmException("请输入验证码","1001");
        }
        String correctCod = (String) redisTemplate.opsForValue().get(map.get("phone")+":dmreg");
        if (!correctCod.equals(map.get("vcode"))){
            throw new DmException("验证码不匹配","1002");
        }

        return VoUtil.returnSuccess("注册成功",dmUserServer.register(map));
    }

    @PostMapping(path = "/upload")
    public String uploadFile(@RequestParam("file")MultipartFile file) {
        return dmUserServer.uploadImage(file);
    }

}
